package skiree.host.abetsy.start;

import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import skiree.host.abetsy.api.annotation.EventQueueServer;
import skiree.host.abetsy.api.service.ConfigService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class StartDanMuListener implements ApplicationRunner {

    private static final Logger logger = LoggerFactory.getLogger(StartDanMuListener.class);

    @Value("${server.port}")
    private String serverPort;

    @Autowired
    private EventQueueServer eventQueueServer;

    @Resource
    private ConfigService configService;

    @Override
    public void run(ApplicationArguments args) {
        eventQueueServer.SettingExecutor(configService.getCoreSize(), configService.getMaxSize());
        // 打印数据信息
        String logTemplate = "Starting ABetsy Server On %s Network %s";
        String urlTemplate = "http://%s:%s";
        List<String> localNets = new ArrayList<>();
        List<String> publicNets = new ArrayList<>();
        for (String ipv4 : NetUtil.localIpv4s()) {
            if (StrUtil.startWithAny(ipv4, "10.", "172.", "192.")) {
                localNets.add(String.format(urlTemplate, ipv4, serverPort));
            } else if (!StrUtil.startWith(ipv4, "127.")) {
                if (NetUtil.ping(ipv4)) {
                    publicNets.add(String.format(urlTemplate, ipv4, serverPort));
                }
            }
        }
        if (!localNets.isEmpty()) {
            logger.info(String.format(logTemplate, "Local", String.join(", ", localNets)));
        }
        if (!publicNets.isEmpty()) {
            logger.info(String.format(logTemplate, "Public", String.join(", ", publicNets)));
        }
    }
}